package io_nio;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

public class ChannelAndBuffer {

    public static void main(String[] args) {
        channelAndBuffer();//循环读取
    }

    private static void channelAndBuffer() {
        FileInputStream fis;
        FileChannel inChannel = null;
        try {
            fis = new FileInputStream("E:\\pp3\\effective-java\\src\\io_nio\\ChannelAndBuffer.java");
            inChannel = fis.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(10);
            Charset charset = Charset.forName("UTF-8");
            CharsetDecoder decoder = charset.newDecoder();
            while (inChannel.read(buffer) != -1){//将管道内容读到缓冲区
                buffer.flip();
                CharBuffer charBuffer = decoder.decode(buffer);
                System.out.println(charBuffer);
                buffer.clear();//虽然clear不清除数据，但是每次读取都会覆盖上一次读取内容
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        } finally {
            try {
                inChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }


    }
}
